/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

/*
 * Created on 23/05/2004
 */

package au.com.lastweekend.jim.io.jpeg.read;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.io.jpeg.HuffmanTable;
import au.com.lastweekend.jim.io.jpeg.HuffmanTableDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegImageDataDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegProcessingException;
import au.com.lastweekend.jim.io.jpeg.JpegRestartIntervalDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegScanDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegSegment;
import au.com.lastweekend.jim.io.jpeg.JpegStartOfFrameDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegStartOfScanDirectory;
import au.com.lastweekend.jim.io.jpeg.Scan;
import au.com.lastweekend.jim.io.metadata.Directory;
import au.com.lastweekend.jim.io.metadata.Metadata;

/**
 * @author <a href="mailto:grant@lastweekend.com.au"> <Grant Gardner> </a>
 * @version $Id: JpegCompressedDataReader.java,v 1.4 2006/02/20 12:21:11 ggardner Exp $
 */
public class JpegCompressedDataReader {

    private static final Logger LOG = Logger.getLogger(JpegCompressedDataReader.class);
    private InputStream _inStream;
    private static final int CHUNK_SIZE = 1024 * 4;

    /**
     * @param inStream
     */
    public JpegCompressedDataReader(InputStream inStream) {

        _inStream = inStream;

    }

    /**
     * Reads JPEG Component coefficient data. This is a lossless process such that this data can be transformed (90 degree
     * rotations, flips, crops) losslessly.
     * 
     * TODO Currently assumes sequential DCT
     * 
     * @param metadata
     * @throws JpegProcessingException
     */
    public void readTransformableData(Metadata metadata) throws JpegProcessingException {

        Scan scan = new Scan();

        JpegStartOfFrameDirectory startOfFrameDirectory = null;
        JpegStartOfScanDirectory startOfScanDirectory = null;

        Iterator<Directory> directoryIterator = metadata.getDirectoryIterator();
        while (directoryIterator.hasNext()) {
            Directory directory = directoryIterator.next();
            if (directory instanceof JpegStartOfFrameDirectory) {
                startOfFrameDirectory = (JpegStartOfFrameDirectory) directory;
            } else if (directory instanceof HuffmanTableDirectory) {
                HuffmanTableDirectory huffmanDirectory = (HuffmanTableDirectory) directory;
                byte tableIndex = huffmanDirectory.getTableID();

                scan.setHuffmanDecoder(huffmanDirectory.isACTable(), tableIndex, new HuffmanTable(huffmanDirectory
                        .getHuffmanValues()));

            } else if (directory instanceof JpegStartOfScanDirectory) {
                startOfScanDirectory = (JpegStartOfScanDirectory) directory;
            } else if (directory instanceof JpegRestartIntervalDirectory) {
                JpegRestartIntervalDirectory restartIntervalDirectory = (JpegRestartIntervalDirectory) directory;
                int restartInterval = restartIntervalDirectory.getRestartInterval();
                scan.setRestartInterval(restartInterval);
            }
        }

        // Create components from Start of Frame information
        byte numberOfComponents = startOfFrameDirectory.getNumberOfComponents();
        int frameWidth = startOfFrameDirectory.getFrameWidth();
        int frameHeight = startOfFrameDirectory.getFrameHeight();
        scan.setHeight(frameHeight);
        scan.setWidth(frameWidth);
        for (int i = 0; i < numberOfComponents; i++) {
            byte componentID = startOfFrameDirectory.getComponentID(i);
            byte horizontalSamplingFactor = startOfFrameDirectory.getHorizontalSamplingFactor(i);
            byte verticalSamplingFactor = startOfFrameDirectory.getVerticalSamplingFactor(i);
            scan.createComponent(componentID, horizontalSamplingFactor, verticalSamplingFactor);
        }

        // Setup Huffman tables from Start of Scan info
        if (numberOfComponents != startOfScanDirectory.getNumberOfComponents()) {
            throw new JpegProcessingException("Mismatched component count in SOF and SOS headers");
        }

        for (int i = 0; i < numberOfComponents; i++) {
            byte componentID = startOfScanDirectory.getComponentID(i);
            byte acDecoderIndex = startOfScanDirectory.getACTableID(i);
            byte dcDecoderIndex = startOfScanDirectory.getDCTableID(i);

            scan.setComponentDecoders(componentID, dcDecoderIndex, acDecoderIndex);
        }
        LOG.debug("Loaded scan info");
        scan.read(_inStream);
        LOG.debug("Read scan");
        checkEndOfImage();

        JpegScanDirectory imageDataDirectory = new JpegScanDirectory();
        imageDataDirectory.setScan(scan);
        metadata.addDirectory(imageDataDirectory);
        LOG.debug("At end of image");
    }

    /**
     * @throws JpegProcessingException
     * 
     */
    private void checkEndOfImage() throws JpegProcessingException {

        try {
            byte markerBoundary = (byte) _inStream.read();
            byte endOfImageMarker = (byte) _inStream.read();
            // Check for a final restart marker...
            if (markerBoundary == JpegSegment.SEGMENT_BOUNDARY && endOfImageMarker >= JpegSegment.RESTARTS_BEGIN
                    && endOfImageMarker <= JpegSegment.RESTARTS_END) {
                LOG.debug("Found terminating restart marker " + Integer.toHexString(endOfImageMarker));
                markerBoundary = (byte) _inStream.read();
                endOfImageMarker = (byte) _inStream.read();
            }

            if (markerBoundary != JpegSegment.SEGMENT_BOUNDARY || endOfImageMarker != JpegSegment.MARKER_EOI) {

                int toEndOfFile = 0;
                while (_inStream.read() >= 0) {
                    toEndOfFile++;
                }
                throw new JpegProcessingException("Expecting end of image markers, but found "
                        + Integer.toHexString(markerBoundary) + ", " + Integer.toHexString(endOfImageMarker) + ", " + toEndOfFile
                        + " bytes from end of file");
            }
        } catch (IOException e) {
            throw new JpegProcessingException(e);
        }

    }

    /**
     * Reads data without any decoding. Useful for writing files with changed metadata (eg changed Exif/IPTC tags) without going
     * through a potentially lossy recompression process.
     * 
     * @param metadata
     * @throws JpegProcessingException
     */
    public void readRawData(Metadata metadata) throws JpegProcessingException {

        boolean endOfImage = false;
        List<byte[]> chunks = new ArrayList<byte[]>();
        int readCount = 0;
        byte prevByte = 0;
        byte[] dataChunk = new byte[CHUNK_SIZE];

        while (!endOfImage) {
            if (readCount == CHUNK_SIZE) {

                chunks.add(dataChunk);
                readCount = 0;
                dataChunk = new byte[CHUNK_SIZE];
            }

            int next;

            try {
                next = _inStream.read();
            } catch (IOException e) {
                throw new JpegProcessingException(e);
            }

            byte nextByte = (byte) (next & 0xFF);

            if (next < 0) {
                throw new JpegProcessingException("End of file before End Of Image marker");
            } else if (prevByte == JpegSegment.SEGMENT_BOUNDARY && nextByte == JpegSegment.MARKER_EOI) {
                readCount--;
                chunks.add(dataChunk);
                endOfImage = true;
            } else {
                prevByte = nextByte;
                dataChunk[readCount] = prevByte;
                readCount++;
            }

        }

        int imageDataSize = (chunks.size() - 1) * CHUNK_SIZE + readCount;
        byte[] imageData = new byte[imageDataSize];
        Iterator<byte[]> iterator = chunks.iterator();
        for (int i = 0; i < imageDataSize; i++) {
            int j = i % CHUNK_SIZE;
            if (j == 0) {
                dataChunk = iterator.next();
            }
            imageData[i] = dataChunk[j];

        }

        metadata.addDirectory(new JpegImageDataDirectory(imageData));
    }

}